/*
   Copyright 2007 Marco Slot (marco.slot@gmail.com)

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package nl.marcoslot.lib.io;

import java.text.CharacterIterator;

/**
 * A few useful functions for parsing with a CharacterIterator.
 * 
 * @author Marco Slot
 */
public final class ParserTools {
    
    private ParserTools() { }
    
    /**
     * Skips over all white space characters.
     * 
     * @param cit 
     *    The CharacterIterator to use.
     */
    public static void skipWhiteSpace(CharacterIterator cit) {
        while(Character.isWhitespace(cit.current())) {
            cit.next();
        }
    }
    
    /**
     * Reads a character from the iterator.
     *
     * @param cit 
     *    The CharacterIterator to use.
     * @return 
     *    The read character.
     */
   public static char readChar(CharacterIterator cit) {
       char result = cit.current();
       cit.next();
       return result;
   }
   
    /**
     * Reads a letter from the character iterator.
     * 
     * @param cit 
     *    The CharacterIterator to use.
     * @param errorMessage 
     *    The error message to use in the ParseException.
     * @throws nl.marcoslot.lib.io.ParseException 
     *    If the read character is not a letter.
     * @return
     *    The letter. 
     */
   public static char readLetter(CharacterIterator cit, String errorMessage) throws ParseException {
       char result = readChar(cit);
       if(!Character.isLetter(result)) {
           throw new ParseException(errorMessage);
       }
       return result;
   }
   
    /**
     * Reads letters and appends them to a String.
     * 
     * @param cit 
     *    The CharacterIterator to use.
     * @return 
     *    The word.
     */
   public static String readWord(CharacterIterator cit){
        StringBuffer buffer;
        
        buffer = new StringBuffer();
        
        while(Character.isLetter(cit.current())) {
            buffer.append(ParserTools.readChar(cit));
        }
        
        return buffer.toString();
   }
   
}
